const {
  CityModel
} = require('../../utils/city-model.js')
const cityModel = new CityModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentCity: '',
    cityCode: '',
    city: []
  },

  bindtap(e) {
    if (this.data.currentCity) {
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      prevPage.setData({
        selectCity: {
          name: e.detail.name,
          code: e.detail.cityCode
        }
      })
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.redirectTo({
        url: `/pages/currencyShop/chooseStore/index?cityCode=${e.detail.cityCode}&cityName=${e.detail.name}&from=home`,
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      currentCity: options.city,
      cityCode: options.cityCode
    })
    cityModel.getCities({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      this.formatCity(data)
    }).catch(err => {
      console.log(err)
    })
  },

  formatCity(data) {
    let resultCity = []
    let hotCity = (data.hotCityList || []).map(item => ({
      ...item,
      name: item.cityName,
      key: "热门"
    }))
    resultCity[0] = {
      title: "国内热门城市",
      type: 'hot',
      item: hotCity
    }
    const city = data.cityManageResult || []
    city.forEach(item => {
      let result = {
        title: item.indexCharacter
      }
      const cityCodeResultList = item.cityCodeResultList || []
      result.item = cityCodeResultList.map(val => ({
        ...val,
        name: val.cityName,
        key: item.indexCharacter
      }))
      resultCity.push(result)
    })
    this.setData({
      city: resultCity
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})